import redis
import json


def connect(host='localhost', port=6379, db=1):
    return redis.StrictRedis(
        host=host,
        port=port,
        db=db,
        decode_responses=True
    )

def opt_redis(conn, data):
    # 擦除redis中的数据
    res = conn.keys("*")
    piped = conn.pipeline()
    if len(res) != 0:
        # piped = conn.pipeline()
        for item in res:
            piped.delete(item)
        # piped.execute()
    # 写入redis
    timestamp = data.get("Time", 0)
    # piped = conn.pipeline()
    for key, value in data.items():
        if key != "Time":
            piped.set(str(timestamp) + "#" + str(key), json.dumps(value))
    piped.execute()
    # redis 写入完毕


def opt_redis_geo(conn, data):
    '''
    使用Redis GEO 重写 
    其原理是改用Redis的zset数据结构，要求使用 Redis 3.2+ 
    参考：https://www.runoob.com/redis/redis-geo.html
    约定键名为 "ship"
    '''
    pipe = conn.pipeline()
    pipe.delete("ship")
    for k, v in data.items():
        if k != "Time":
            lon = v.get("lon")
            lat = v.get("lat")
            pipe.geoadd("ship", lon, lat, json.dumps(v))
    pipe.execute()


def test():
    conn = connect()
    data = {'Time': 79, 
        '2130002': {'Time': 79, 'type': 15, 'mmsi': 2130002, 'length': 10.0, 'width': 5.0, 'sName': 'Ferry0.48704', 'lon': 118.61926983679224, 'lat': 31.94813711053066, 'head': 125.03431546647238, 'rot': 0.3214551227779962, 'speed': 4.1156, 'next': 1, 'DCPA': 95.38681144015762, 'TCPA': 40.58194685963921, 'risk_ship': '2130003', 'collision_risk': 0.8171687162980449, 'VOargs': {'VOPxy': [[276.47633735089005, 93.41068825334432], [0, 0], [-3.363190173432507, -2.3721541308464626], [-10.013376778689338, 17.31277809787869], [2.5374482406143923, -19.83838089268353], [17.086660574897508, 10.39451924670102], [19.77291304076767, -3.0053136064392607], [-11.389280875329357, -16.44032484986151], [11.389280875222699, 16.440324849461184]], 'status': 0, 'head': 124.71286034369439, 'speed': 4.1156, 'radius': 20}}, 
        '2130003': {'Time': 79, 'type': 15, 'mmsi': 2130003, 'length': 10.0, 'width': 5.0, 'lon': 118.62212412227007, 'lat': 31.948975688572357, 'head': 234.80357092536508, 'rot': 0.0, 'speed': 4.1156, 'next': 1}}
    opt_redis(conn, data)

# def main():
#     test()


# if __name__ == "__main__":
#     main()
